package com.siyoumi.app.sys.service.impl;

import com.siyoumi.app.sys.service.WxTokenService;
import com.siyoumi.app.sys.service.wxapi.ApiConfig;
import com.siyoumi.app.sys.service.wxapi.WxApiOpen;
import com.siyoumi.entity.SysAccsuperConfig;
import com.siyoumi.service.SysAccsuperConfigService;
import com.siyoumi.util.XReturn;
import com.siyoumi.validator.XValidator;
import lombok.extern.slf4j.Slf4j;

//开放平台-授权站点
@Slf4j
public class WxTokenServiceWxOpenClientImpl
        extends WxTokenService {

    @Override
    protected String getApiToken(SysAccsuperConfig entityConfig) {
        ApiConfig apiConfig = new ApiConfig();
        apiConfig.setAppId(entityConfig.getAconfig_app_id());
        apiConfig.setAppSecret(entityConfig.getAconfig_app_secret());

        SysAccsuperConfig entityConfigParent = SysAccsuperConfigService.getBean().getXConfigWxOpenParent(entityConfig.getX());
        ApiConfig apiConfigParent = new ApiConfig();
        apiConfigParent.setAppId(entityConfigParent.getAconfig_app_id());
        apiConfigParent.setAccessToken(WxTokenService.getBean(entityConfigParent).getAccessToken());
        //设置主站点
        apiConfig.setParent(apiConfigParent);

        WxApiOpen api = WxApiOpen.getIns(null);
        api.setConfig(apiConfig);
        XReturn r = api.clientToken(entityConfig.getAconfig_refresh_token());
        if (r.err()) {
            XValidator.err(r);
        }

        String refreshToken = r.getData("authorizer_refresh_token");
        String accessToken = r.getData("authorizer_access_token");
        log.debug("authorizer_refresh_token: {}", refreshToken);
        SysAccsuperConfig entityConfigUpdate = new SysAccsuperConfig();
        entityConfigUpdate.setAconfig_id(entityConfig.getKey());
        entityConfigUpdate.setAconfig_refresh_token(refreshToken);
        SysAccsuperConfigService.getBean().saveOrUpdatePassEqualField(entityConfig, entityConfigUpdate);

        return accessToken;
    }

    @Override
    protected String getApiJsTicket(SysAccsuperConfig entityConfig) {
        return null;
    }
}
